/*!
 * Page: pages/vip/Vip
 * License: MIT
 * Created: 2019-11-21 14:40
 */

import { GlobalData } from '/store/state'
import { userApi } from '/api/user'
import { getServer, vipTime, getAppId, checkUserisVip } from '/store/mutations'
import { $event } from '/utils'
import { getDomoUser } from '/store/actions'
// import { getServer } from '/store/mutations'
Page({
  data: {
    num0: 3,
    num1: 7,
    privilege0: [
      {
        img: 'privilege',
        title: '专属头像标识',
      },
      {
        img: 'mall',
        title: '专享商品会员价',
      },
      {
        img: 'jifen',
        title: '赠送1000积分',
      },
    ],
    privilege1: [
      {
        img: 'privilege',
        title: '专属头像标识',
      },
      {
        img: 'mall',
        title: '专享商品会员价',
      },
      {
        img: 'jifen',
        title: '赠送1000积分',
      },
      {
        img: 'authentication',
        title: '快速认证先认证后审核',
      },
      {
        img: 'exclusive',
        title: '专属会员活动',
      },
      {
        img: 'knowledge',
        title: '专享知识会员价',
      },
      {
        img: 'hot',
        title: '增加热门曝光机会',
      },
    ],
    number: 199 /**会员价格 */,
    agree: false,
    /** 1金卡，2黑卡 */
    current: 0,
    vip: {} as DomoVip,
    priceIndex: 0,
    duration: 1,
    level: '',
    submitLock: false,
    upVip: '',
    user: {} as DomoUser,
    /** 是否过期 */
    expire: false,
  },
  async onLoad() {
    if (GlobalData.system === 'ios') {
      wx.showToast({
        title: '由于相关规范，iOS功能暂不可用',
        icon: 'none',
      })
      return
    }
    $event.on('logged', this, async () => {
      this.getUserInfo()
    })
    this.getPosition()
    await this.getVipInfo()
    await this.getUserInfo()
  },
  getPosition() {
    this.setData({
      navigationHeight: GlobalData.navigationHeight,
    })
  },
  /** 会员卡配置信息 */
  async getVipInfo() {
    const vipData = await userApi.getVipConfig()
    /** 处理VIP数据,取成自己想要的格式 */
    const vip = {} as DomoVip
    vip.switch = vipData.switch
    vip.config = []
    vipData.config.low && vipData.config.low.enable ? vip.config.push(vipData.config.low) : ''
    vipData.config.middle && vipData.config.middle.enable
      ? vip.config.push(vipData.config.middle)
      : ''
    vipData.config.high && vipData.config.high.enable ? vip.config.push(vipData.config.high) : ''
    vip.config = vip.config.filter((item: DomoVipItem) => {
      return (item.setting = item.setting.filter((items) => {
        return items.enable
      }))
    })
    if (vipData.config.low.createPrivateTopic) {
      this.setData({
        privilege0: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'circle',
            title: `专属私密圈子${vipData.config.low.topic_num}个`,
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              vip.config[0].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
        ],
        num0: 4,
      })
    } else {
      this.setData({
        privilege0: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              vip.config[0].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
        ],
        num0: 3,
      })
    }
    if (vipData.config.middle.createPrivateTopic) {
      this.setData({
        privilege1: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'circle',
            title: `专属私密圈子${vipData.config.middle.topic_num}个`,
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              vip.config[1].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
          {
            img: 'authentication',
            title: '快速认证先认证后审核',
          },
          {
            img: 'exclusive',
            title: '专属会员活动',
          },
          {
            img: 'knowledge',
            title: '专享知识会员价',
          },
          {
            img: 'hot',
            title: '增加热门曝光机会',
          },
        ],
        num1: 8,
      })
    } else {
      this.setData({
        privilege1: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              vip.config[1].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
          {
            img: 'authentication',
            title: '快速认证先认证后审核',
          },
          {
            img: 'exclusive',
            title: '专属会员活动',
          },
          {
            img: 'knowledge',
            title: '专享知识会员价',
          },
          {
            img: 'hot',
            title: '增加热门曝光机会',
          },
        ],
        num0: 7,
      })
    }
    this.setData({
      vip,
      level: vip.config[0].level,
    })
  },
  /**
   * 获取用户信息及用户圈子
   */
  async getUserInfo() {
    const user = wx.getStorageSync(`${getServer()}/logged`).data || {}
    let expire = false
    if (user.vip) {
      expire = !checkUserisVip(user)
      const time = new Date(user.vip.end_time)
      user.vipTime = vipTime(time)
    }
    this.setData({
      user,
      expire,
    })
  },
  /** 同意协议 */
  agree() {
    this.setData({
      agree: !this.data.agree,
    })
  },
  /** 跳转会员协议 */
  protocol() {
    wx.navigateTo({
      url: '/mine/aboutus/aboutus?type=vip_protrol',
    })
  },
  /** 会员卡切换 */
  cardChange(e: WechatMiniprogram.SwiperChange) {
    const {
      detail: { current },
    } = e
    this.setData({
      current,
      level: this.data.vip.config[current].level,
    })
  },
  /** 选择购买会员期限 */
  chooseVipPrice(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { index, type },
      },
    } = e
    this.setData({
      priceIndex: +index,
      duration: +type,
    })

    if (this.data.vip.config[0].createPrivateTopic) {
      this.setData({
        privilege0: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'circle',
            title: `专属私密圈子${this.data.vip.config[0].topic_num}个`,
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              this.data.vip.config[0].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
        ],
        num0: 4,
      })
    } else {
      this.setData({
        privilege0: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              this.data.vip.config[0].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
        ],
        num0: 3,
      })
    }
    if (this.data.vip.config[1].createPrivateTopic) {
      this.setData({
        privilege1: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'circle',
            title: `专属私密圈子${this.data.vip.config[1].topic_num}个`,
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              this.data.vip.config[1].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
          {
            img: 'authentication',
            title: '快速认证先认证后审核',
          },
          {
            img: 'exclusive',
            title: '专属会员活动',
          },
          {
            img: 'knowledge',
            title: '专享知识会员价',
          },
          {
            img: 'hot',
            title: '增加热门曝光机会',
          },
        ],
        num1: 8,
      })
    } else {
      this.setData({
        privilege1: [
          {
            img: 'privilege',
            title: '专属头像标识',
          },
          {
            img: 'mall',
            title: '专享商品会员价',
          },
          {
            img: 'jifen',
            title:
              '赠送' +
              this.data.vip.config[1].setting[this.data.priceIndex].currency +
              GlobalData.currencyName,
          },
          {
            img: 'authentication',
            title: '快速认证先认证后审核',
          },
          {
            img: 'exclusive',
            title: '专属会员活动',
          },
          {
            img: 'knowledge',
            title: '专享知识会员价',
          },
          {
            img: 'hot',
            title: '增加热门曝光机会',
          },
        ],
        num0: 7,
      })
    }
  },
  /** 购买 */
  async buy() {
    if (this.data.submitLock) return
    if (!this.data.vip) {
      wx.showToast({
        title: '暂时不能购买此类会员',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    if (!this.data.agree) {
      wx.showToast({
        title: '请同意《会员服务协议》',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    this.setData({ submitLock: true })
    const { duration, level } = this.data
    try {
      const timezoneoffset = -Math.floor(Math.abs(new Date().getTimezoneOffset() / 60))
      const timezone =
        timezoneoffset >= 0 ? `+0${timezoneoffset}:00` : `-0${Math.abs(timezoneoffset)}:00`
      const payInfo = await userApi.creatVipOrder({
        duration,
        level,
        quantity: 1,
        pay_method: 'WechatPay_Js',
        timezone,
        openid: wx.getStorageSync(`${getServer()}/openId`).data,
        appid: getAppId() ? getAppId() : '{{APP_ID}}',
        app_type: 'micro',
      })
      if (payInfo.pay_amount === 0) {
        wx.showToast({
          title: '购买成功',
        })
        return
      }
      wx.requestPayment({
        ...payInfo.pay_data,
        success: () => {
          wx.showLoading({
            title: '支付中',
          })
          setTimeout(() => {
            wx.hideLoading()
            getDomoUser()
            wx.navigateBack({ delta: 1 })
          }, 3000)
        },
        fail: () => {
          wx.showToast({
            title: '购买失败',
            icon: 'none',
          })
        },
      })
      getDomoUser()
      this.setData({
        submitLock: false,
      })
    } catch (error) {
      wx.showToast({ title: `${error.data.message}`, icon: 'none' })
      this.setData({
        submitLock: false,
      })
    }
  },
})
